<template>
  <div class="admin-main">
    <a-button v-if="isAuth('system:admin:add')" class="editable-add-btn" @click="editHandleOpen('add')">添加</a-button>
    <a-divider type="vertical" />
    <a-button v-if="isAuth('system:admin:delete')" type="danger" class="editable-add-btn" @click="deleteHandleOk(selectedRowKeys)">删除</a-button>
    <div>
      <br />
    </div>

    <a-table
      :columns="columns"
      :data-source="adminList"
      :pagination="{current:admins.pageNum,total:admins.total}"
      :row-selection="{onChange: onChange,onSelectAll:onSelectAll ,onSelect:onSelect}"
      :rowKey="record=>record.id"
      @change="handleTableChange"
    >
      <template slot="avatar" slot-scope="avatar">
        <template v-if="avatar">
          <a-avatar size="small" class="avatar" :src="baseURL+avatar" />
        </template>
        <template v-else>无</template>
      </template>
      <template slot="status" slot-scope="status">
        <a-tag v-if="status===0" color="red">禁用</a-tag>
        <a-tag v-else-if="status===1" color="green">正常</a-tag>
      </template>
      <template slot="action" slot-scope="text, record">
        <a-divider type="vertical" />
        <a v-if="isAuth('system:admin:delete')" @click="deleteHandleOk(record.id)">删除</a>
        <a-divider type="vertical" />
        <a v-if="isAuth('system:admin:update')" @click="editHandleOpen('update',record.id)">编辑</a>
      </template>
    </a-table>

    <a-modal
      title="编辑"
      :footer="null"
      :visible="editVisible"
      :confirm-loading="editConfirmLoading"
      @cancel="editHandleCancel"
    >
      <a-form-model ref="editForm" :rules="editRules" :model="editForm">
        <a-form-model-item label="名称" prop="name">
          <a-input v-model="editForm.name" />
        </a-form-model-item>
        <a-form-model-item label="用户名" prop="username">
          <a-input v-model="editForm.username" />
        </a-form-model-item>
        <a-form-model-item label="密码" prop="password">
          <a-input type="password" v-model="editForm.password" />
        </a-form-model-item>
        <a-form-model-item label="头像" prop="avatar">
          <a-upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :customRequest="uploadAvatar"
            :before-upload="beforeUpload"
            @change="uploadhandleChange"
          >
            <img v-if="editForm.avatar" :src="baseURL+editForm.avatar" alt="avatar" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item label="状态">
          <a-radio-group v-model="editForm.status" :default-value="editForm.status">
            <a-radio :value="1">正常</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="排序">
          <a-input v-model="editForm.sort" />
        </a-form-model-item>
        <a-form-model-item label="角色">
          <a-tree-select
            v-model="editForm.roleIds"
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="roleAll"
            placeholder="Please select"
            allow-clear
            multiple
            tree-default-expand-all
            :replaceFields="{children:'children', title:'name', key:'id', value: 'id' }"
            @change="handleChange"
            @search="handleSearch"
            @select="handleSelect"
          />
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" @click="editHandleOk">提交</a-button>
          <a-button style="margin-left: 10px;" @click="editHandleCancel">取消</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>
<style scoped>
.admin-main {
  position: relative;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.ant-upload-picture-card-wrapper{ overflow: auto; height: 250px;}
</style>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
import {getBase64,baseURL} from "@/util/index"


export default {
  data() {
    return {
      baseURL,
      columns: [
        {
          title: "id",
          dataIndex: "id"
        },
        {
          title: "名称",
          dataIndex: "name"
        },
        {
          title: "用户名",
          dataIndex: "username"
        },
        {
          title: "头像",
          dataIndex: "avatar",
          scopedSlots: { customRender: "avatar" }
        },
        {
          title: "状态",
          dataIndex: "status",
          scopedSlots: { customRender: "status" }
        },
        {
          title: "排序",
          dataIndex: "sort"
        },
        {
          title: "创建时间",
          dataIndex: "createTime"
        },
        {
          title: "操作",
          scopedSlots: { customRender: "action" }
        }
      ],
      selectedRowKeys: [],
      modalType: "",
      editVisible: false,
      editConfirmLoading: false,
      editForm: {
        roleIds: [],
        id: 0,
        name: "",
        username: "",
        password: "",
        avatar: "",
        status: 1,
        sort: 0
      },
      editRules: {
        name: [{ required: true, message: "请填写名称", trigger: "change" }],

        username: [{ required: true, message: "请填写用户名", trigger: "change" }],

        password: [{ required: true, message: "请填写密码", trigger: "change" }]
      },
      loading: false,
      
 
    };
  },

  computed: {
    ...mapState("admin", ["admins", "admin"]),
    ...mapGetters("admin", ["adminList","roleAll"])
  },
  created() {
    this.GET_ADMINS({ page: this.admins.pageNum, size: 10 });
    this.GET_ROLES();
  },
  methods: {
    ...mapMutations("admin", ["SET_ADMIN"]),
    ...mapActions("admin", [
      "GET_ADMINS",
      "ADD_ADMIN",
      "GET_ADMIN_BY_ID",
      "UPDATE_ADMIN",
      "DELETE_ADMIN_BY_IDS",
      "UPLOAD_AVATAR"
    ]),
    ...mapActions("role", ["GET_ROLES"]),
    onChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
    },
    onSelect(record, selected, selectedRows) {},
    onSelectAll(selected, selectedRows, changeRows) {},
    handleChange(value) {
      console.log(value);
      this.value = value;
    },
    handleSearch() {
      console.log(...arguments);
    },
    handleSelect() {
      console.log(...arguments);
    },
    handleTableChange(pagination, filters, sorter) {
      this.GET_ADMINS({ page: pagination.current, size: 10 });
    },
    editHandleOpen(modalType, id) {
      this.modalType = modalType;
      if (this.modalType === "update" && id) {
        this.GET_ADMIN_BY_ID(id)
          .then(response => {
            const {
              roleIds,
              id,
              name,
              username,
              password,
              avatar,
              status,
              sort
            } = this.admin;
            this.editForm.roleIds = roleIds;
            this.editForm.id = id;
            this.editForm.name = name;
            this.editForm.username = username;
            this.editForm.password = password;
            this.editForm.avatar = avatar;
            this.editForm.status = status;
            this.editForm.sort = sort;
          })
          .catch(error => {
            this.$message.error(error);
          });
      }

      if (this.modalType === "add" && !id) {
        this.editForm.roleIds = [];
        this.editForm.id = 0;
        this.editForm.name = "";
        this.editForm.username = "";
        this.editForm.password = "";
        this.editForm.avatar = "";
        this.editForm.status = 1;
        this.editForm.sort = 0;
        this.SET_ADMIN(this.editForm);
      }
      this.editVisible = true;
    },
    editHandleOk() {
      let flag = true;
      this.$refs.editForm.validate(valid => {
        if (!valid) {
          this.$message.error("提交失败");
          flag = false;
        }
      });

      if (flag) {
        this.editConfirmLoading = true;

        if (this.modalType === "add") {
          this.ADD_ADMIN(this.editForm)
            .then(response => {
              this.$message.success(response);
              this.GET_ADMINS();
            })
            .catch(error => {
              this.$message.error(error);
              this.GET_ADMINS();
            });
        }

        if (this.modalType === "update") {
          this.UPDATE_ADMIN(this.editForm)
            .then(response => {
              this.$message.success(response);
              this.GET_ADMINS();
            })
            .catch(error => {
              this.$message.error(error);
              this.GET_ADMINS();
            });
        }

        this.modalType = "";
        this.editVisible = false;
        this.editConfirmLoading = false;
      }
    },
    editHandleCancel() {
      this.modalType = "";
      this.editVisible = false;
    },

    deleteHandleOk(ids) {
      this.DELETE_ADMIN_BY_IDS(ids)
        .then(response => {
          this.$message.success(response);
          this.GET_ADMINS();
        })
        .catch(error => {
          this.$message.error(error);
          this.GET_ADMINS();
        });
    },
    uploadAvatar(data){
      var formData = new FormData();
      const {file} = data
      formData.append("avatar",file)
      formData.append("id",this.editForm.id)
      this.UPLOAD_AVATAR(formData).then(response=>{
        this.editForm.avatar=this.admin.avatar
        this.$message.success(response);
      }).catch(error=>{
        this.$message.error(error);
      })

    },
    uploadhandleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true;
        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.editForm.avatar = imageUrl;
          this.loading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M;
    },
 



  }
};
</script>
